
jQuery.fn.highlight = function(pat) {
    function innerHighlight(node, pat) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pat);
            if (pos >= 0) {
                var spannode = document.createElement('span');
                spannode.className = 'mdd-fc-bold';
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pat.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                skip = 1;
            }
        }
        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerHighlight(node.childNodes[i], pat);
            }
        }
        return skip;
    }
    return this.length && pat && pat.length ? this.each(function() {
        innerHighlight(this, pat.toUpperCase());
    }) : this;
};

jQuery.fn.removeHighlight = function() {
    return this.find("span.highlight").each(function() {
        this.parentNode.firstChild.nodeName;
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
            }
    }).end();
};

function beforeSubmitDownloadZip()
{
    // Takes in a list of files to be downloaded from .downloads
  
    var downloads_container =new Array();
    $('.downloads').each(function(){
        downloads_container.push($(this).val());
    });
    
    $('#mdd-fc-filearray').attr('value',''+downloads_container);
    if(downloads_container.length<=0){
        return false
     
    }  

  
    return true;
}
function enableDataCart(){
    if(document.URL.indexOf("download.html") >= 0){ 
        //alert($.cookie("mdd-fc-dcc"));
        
        
        $("#download-table tr").each(function(){
            var x =$(this);
            if(x.children().length == 4){
              
                x.append("<td><input class='pdf-checkbox' type='checkbox'/></td>");
                    
            }
                
        });//whatever
        var transformer = new $.Zebra_TransForm();
        
        if($.cookie("mdd-fc-dcc")!= null && $.cookie("mdd-fc-dcc")!= ""){
            $("#datacart-table").html($.cookie("mdd-fc-dcc"));
            $("#datacart-table input").each(function(){
                
                
                $("#download-table").find("a[href*='"+$(this).val()+"']").parent().parent().find("input").trigger("click");
                    

            });
        }
        //download title gone, replace?
        $("#download-table tbody tr:eq(1)").append("<td></td><td></td>");
            
        //enable checkbox logic

        $(".pdf-checkbox").change(function(){
             
            var temp= $(this).parent().prev().prev().prev().prev();
            var templink= $(this).parent().prev().prev().prev().prev().children().get(0);
            
            if($(this).attr("checked")=="checked"){
                $("#datacart-table").append("<tr><td >"+temp.text()+"<input class='downloads' type='hidden' value='"+$(templink).attr('href')+"'/>"+"</td>");
            }
            else{
                      
                //$("#datacart-table td:contains("+temp.text()+")").parent().remove();
                $("#datacart-table td").each(function(){
                    if($(this).text().trim()==temp.text().trim()){
                        $(this).parent().remove();    
                    }
                   
                });
                
            }
            $.cookie("mdd-fc-dcc",$("#datacart-table").html(),{
                expires: 30
            });
            
            if( $("input[type='checkbox']:checked").length > 0){
                $('#mdd-fc-submit').removeAttr("disabled");
            }else{
                $('#mdd-fc-submit').attr("disabled", "disabled");
            
            }
        });
        //enable clear button
        
        
        $('#mdd-fc-dlclear').click(function(){
            
            $('.downloads').html("");
            $('#datacart-table').html("");
            
            $("input[type='checkbox']").each( function() {
                
                $(this).removeAttr("checked");
                $(".Zebra_TransForm_Checkbox_Checked").each( function() {
                    
                    $(this).removeClass("Zebra_TransForm_Checkbox_Checked");
                });
                
                
                
            });
            $.cookie("mdd-fc-dcc","",{
                expires: 30
            });
        });
       
        //enable download as zip button
        if( $("input[type='checkbox']:checked").length > 0){
            $('#mdd-fc-submit').removeAttr("disabled");
        }else{
            $('#mdd-fc-submit').attr("disabled", "disabled");
            
        }
        $('#mdd-fc-submdit').click(function(){
            if( $("input[type='checkbox']:checked").length > 0){
            //ajaxDownload();
                
                
            }
            else {
                alert(LANG.no_files_selected_datacart);
            }
            return false;
        
        /**    $('input[name=thename]:checked');

            // Takes in a list of files to be downloaded from .downloads
            var downloads_container =new Array();
            $('.downloads').each(function(){
                downloads_container.push($(this).val());
            });
            alert(downloads_container);
        
            var __onSuccess = function(data) {
                // Opens the request in a new window to prevent the current from being modified or redirected
                var OpenWindow=window.open('', '_blank');
                OpenWindow.document.write(data);
                OpenWindow.document.close();
                self.name="main";
       
            };
            var options = {
        
                success: __onSuccess,
                data : {
                    result:''+downloads_container
                }
            //,              url : 'asyncGetFiles'
        
            };
            $('#uploadForm').ajaxForm(options);
            **/
        });
    }
}
function enableSearch(){
    //getting rid of the href and setting the cookie if it exists
    //not in use until further notice.
    if ($(".autoSearchForm .autoSearchFormButton").length){
        
        $(".autoSearchForm .autoSearchFormButton a").attr("href","#");
        
        if($.cookie("siegfried-search") != null){
        // $('#tx_rzautocomplete_pi1_word').val($.cookie("siegfried-search"));
        }
        
    }
    // creates cookie and sends the page to search.html
    //TODO add the english version
    $('.autoSearchFormButton a').click(function(){
        
        $.cookie("siegfried-search",$('#tx_rzautocomplete_pi1_word').val().trim(),{
            expires: 30
        });
        
        window.open ('suche.html','_self',false)


            
        
    });//end function
    
    //enables the enter keypress, adds the value to the cookie and repeats the above function
    //TODO: add the german message of alert
    $('#tx_rzautocomplete_pi1_word').keypress(function(e){
        
        if(e.which == 13){
            
            $.cookie("siegfried-search",$('#tx_rzautocomplete_pi1_word').val().trim(),{
                expires: 30
            });
            
        
            window.open ('suche.html','_self',false)
            
        }
    });//end function
    
    
    //if document loads search html/ set the cookie and call ajax search
    if(document.URL.indexOf("suche.html") >= 0){ 
        
        $(".autoSearchForm").remove();
        
        $('#search_string').val($.cookie("siegfried-search"));
        if($('#search_string').val() != ""){
            ajaxSearch();
        }
    }
    //if document loads search html/ set the cookie and call ajax search // enter enabled version
    //TODO: add the german message of alert
    $('#search_string').keypress(function(e){
        
        if(e.which == 13){
            if($('#search_string').val() != ""){
                $.cookie("siegfried-search",$('#search_string').val().trim(),{
                    expires: 30
                });
                
                ajaxSearch();
           
            }else{
                alert(LANG.fill_search_please);
            }
        
        }

    });

    //if document loads search html/ set the cookie and call ajax search // non enter enabled version
    //TODO: add the german message of alert
    $('#search_submit').click(function(){
        
        if($('#search_string').val() != ""){
            $.cookie("siegfried-search",$('#search_string').val().trim(),{
                expires: 30
            });
            
            ajaxSearch();
           
        }else{
            alert(LANG.fill_search_please);
            
        }
        
    });
}
function ajaxSearch()
{
    $("#responseBlock").html("");
    var __beforeSend= function(){         };
    var __onComplete = function(){
            
    };
    var __onSuccess = function(data,textStatus) {
            
        $("#responseBlock").html(data);
        $(".mdd-fc-srhighlight").highlight($.cookie("siegfried-search"),"mdd-fc-bold");
        var transformer = new $.Zebra_TransForm();
        transformer.update();
    };
      
    var __onError = function(xmlHttpRequest,textStatus,errorThrown) {
            
    };

    jQuery.ajax(
    {
        type : 'POST',
        data : {
            "data":$('#search_string').val().trim(),
            "casesensitive":$('#search_case').is(':checked')?"true":"",
            "word":$('#search_word').is(':checked')?"true":"",
            "table":$('#search_table').is(':checked')?"true":"",
            "lang":$('#search_lang').val()
            

        },
        url : '../../Search/asyncSearch',
        success: __onSuccess,
        error: __onError,
        beforeSend: __beforeSend,
        complete: __onComplete
    });

    return;
}
function enableClearDataCart(){
    $('.mdd-fc-clearbox').unbind();
    $('.mdd-fc-clearbox').click(function(){
        
        $.cookie("mdd-fc-dcc","",{
            expires: 30
        });
        $(".mdd-fc-datacartbox").html("");
        $('#mdd-fc-dcaddbutton').val(LANG.add_to_datacart);
        return false;
    });
}
function enableDataCartOnElementPages(){
    //looks for datacart html to enable functionality
    if($('.mdd-fc-datacartbox').length >0){
         
        if($.cookie("mdd-fc-dcc")!= null && $.cookie("mdd-fc-dcc")!= ""){
            $(".mdd-fc-datacartbox").html($.cookie("mdd-fc-dcc"));
        
        
        }
    }else{
        return;
    }
    
    //iterates the values inside the cookie html and if it finds the page's matching value, sets the button to delete' 
    $(".mdd-fc-datacartbox input").each(function(){
         
        if($('#mdd-fc-dcaddvalue').val()==$(this).val()){
            $('#mdd-fc-dcaddbutton').val(LANG.delete_from_datacart);
        }
    });
    $('#mdd-fc-dcaddbutton').qtip({
        content: {
            text: $('.mdd-fc-tooltip-wrapper').html()
        },
        position: {
            corner: {
                target: 'bottomRight',
                tooltip: 'topRight'
            }
        },
      
        show: 'mouseover',
        hide: {
            when: 'mouseout', 
            fixed: true
        },
        api: {
            onShow: function() { 
                enableClearDataCart();
            }
        }

    });
   
    //enables the addbutton, and tooltips functionality
    $('#mdd-fc-dcaddbutton').click(function(){
        
        
        if($(".mdd-fc-datacartbox td:contains("+$('#mdd-fc-dcaddtitle').val()+")").length >0){
            //alert( $("#mdd-fc-datacartbox").html());
            
            $(".mdd-fc-datacartbox td:contains("+$('#mdd-fc-dcaddtitle').val()+")").parent().remove();
            
            
            $.cookie("mdd-fc-dcc",$(".mdd-fc-datacartbox").html(),{
                expires: 30
                
            });
            $("#mdd-fc-dcaddbutton").qtip('option', 'content.text', $('#mdd-fc-tooltip-wrapper'));
            $("#mdd-fc-dcaddbutton").qtip("show"); 
            enableClearDataCart();
            $('#mdd-fc-dcaddbutton').val(LANG.add_to_datacart);
        
        }else{
            $(".mdd-fc-datacartbox").append("<tr><td >"+$('#mdd-fc-dcaddtitle').val()+"<input class='downloads' type='hidden' value='"+$('#mdd-fc-dcaddvalue').val()+"'/>"+"</td>");
            
            $.cookie("mdd-fc-dcc",$(".mdd-fc-datacartbox").html(),{
                expires: 30
                
            });
            $("#mdd-fc-dcaddbutton").qtip('option', 'content.text', $('#mdd-fc-tooltip-wrapper'));
            $("#mdd-fc-dcaddbutton").qtip("show");
            enableClearDataCart();
            
              
            $('#mdd-fc-dcaddbutton').val(LANG.delete_from_datacart);
            
        }
              
    });
}
//javascript start--
//
function highlightTerm(){
    $.cookie("siegfried-search");
    $.cookie("siegfried-search-highlight","true",{
        expires: 30
    });
}


$(document).ready(function()
{
    //alert(LANG.txt1); 
    
    enableSearch();
    enableDataCart();
    enableDataCartOnElementPages();
    var check = function(){
        if(false){
        // run when condition is met
        }
        else {
            setTimeout(check, 1000); // check again in a second
        }
    }
    if($.cookie("siegfried-search-highlight") == "true"){
        
        $.cookie("siegfried-search-highlight","false",{
            expires: 30
        });
        
        $(".contentMain").highlight($.cookie("siegfried-search"),"mdd-fc-bold");
        //$(".contentMain .mddBar .mdd-fc-bold").parent().click(); 
        
        $(".mdd-fc-bold").closest(".mddBarContent").prev().click();
        check();
        $('html, body').animate({
            scrollTop: $(".mdd-fc-bold").offset().top
            }, 2000);
        
    }
    
    
    if (!String.prototype.trim) {
        String.prototype.trim=function(){
            return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        };

        String.prototype.ltrim=function(){
            return this.replace(/^\s+/,'');
        };

        String.prototype.rtrim=function(){
            return this.replace(/\s+$/,'');
        };

        String.prototype.fulltrim=function(){
            return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
        };
    }
 
   
//ajaxDownload();
});
$(window).resize(function() {
    var transformer = new $.Zebra_TransForm();
    transformer.update();
});
